package com.situ.shoplookweb.api;

import com.situ.shoplook.common.mapper.ShoppingCartMapper;
import com.situ.shoplook.common.model.Result;
import com.situ.shoplook.common.model.User;
import com.situ.shoplook.common.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.jasypt.util.password.PasswordEncryptor;
import org.jasypt.util.password.StrongPasswordEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @Author xinchen
 * @Date: 2024/09/04/ 10:10
 * @Description
 */
@RestController
@RequestMapping(value = "/personal", produces = "application/json;charset=utf-8")
public class loginApi {

    // 单例模式，对数据进行加密
    private static final PasswordEncryptor passwordEncryptor = new StrongPasswordEncryptor();
    @Autowired
    private UserService userService;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    /**
     * 注册逻辑
     */
    @PostMapping("/register")
    public Map<String,Object> register(@RequestParam("loginName") String loginName,
                                 @RequestParam("password") String password,
                                 HttpSession httpSession) {
        if (!StringUtils.hasText(loginName)) {
            return Map.of("code", 400, "msg", "用户名不能为空");
        }
        if (!StringUtils.hasText(password)) {
            return Map.of("code", 400, "msg", "密码不能为空");
        }
        Map<String,Object> registerResult = userService.register(loginName, password);
        return registerResult;
    }

    /**
     * 登录操作
     */

    @PostMapping("/login")
    public Map<String,Object> login(@RequestParam("loginName") String loginName,
                              @RequestParam("password") String password,
                              HttpSession httpSession) {

        if (!StringUtils.hasText(loginName)) {
            return Map.of("code", 400, "msg", "用户名不能为空");
        }
        if (!StringUtils.hasText(password)) {
            return Map.of("code", 400, "msg", "密码不能为空");
        }
        Map<String,Object> map = userService.login(loginName, password, httpSession);

        return map;
    }


    /**
     * 更新信息逻辑
     */
    @PostMapping("/updateInfo")
    public Map<String,Object> updateInfo(@RequestBody User user,HttpSession session){
        try {
            /**
             * 清楚缓存
             */
            session.removeAttribute("newBeeMallUser");
            User user1 = this.userService.findById(user.getUserId());
            int update = this.userService.update(user1);
            //查询更新后的数据
            session.setAttribute("newBeeMallUser", user1);
            return Map.of("code", 200, "msg", "更新成功");
        } catch (Exception e) {
            return Map.of("code", 400, "msg", e.getMessage());
        }
    }
}
